package com.gitee.wsl.logger


import android.os.Build
import android.util.Log
import androidx.annotation.ChecksSdkIntAtLeast
import com.gitee.wsl.ext.toMessage

class AndroidLogPrinter(
    private val maxTagLength: Int = DEFAULT_MAX_TAG_LENGTH,
) : LogPrinter {

    override fun log(level: LogLevel, tag: String, messageAny: Any?, throwable: Throwable?) {
        val androidPriority = level.toAndroidPriority()
        val androidTag = tag.takeIf { it.length > maxTagLength && !isNougatOrHigher() }
            ?.substring(0, maxTagLength)
            ?: tag

        val thread = Thread.currentThread().run { "$name:$id" }
        val composed = "($thread) $messageAny"
        val finalMessage = throwable?.let {
            "$composed\n${it.toMessage}"
        } ?: composed

        Log.println(androidPriority, androidTag, finalMessage)
    }

    @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.N)
    private fun isNougatOrHigher() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N

    companion object{
        internal const val DEFAULT_MAX_TAG_LENGTH = 23
        val INSTANCE = AndroidLogPrinter()
    }
}

private fun LogLevel.toAndroidPriority(): Int {
    return when (this) {
        LogLevel.VERBOSE -> Log.VERBOSE
        LogLevel.DEBUG -> Log.DEBUG
        LogLevel.INFO -> Log.INFO
        LogLevel.WARNING -> Log.WARN
        LogLevel.ERROR -> Log.ERROR
        LogLevel.WTF -> Log.ASSERT
    }
}
